package cases

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/core/validation"
	"github.com/beego/beego/v2/server/web/pagination"
	"log"
	"strconv"
	"strings"
	"xpms/controllers"
	"xpms/cores"
	"xpms/cores/utils"
)

// 用例管理
type CaseController struct {
	controllers.BaseController
}

// @Title 分页查询项目用例管理数据
// @Description 分页查询项目用例管理数据
// @Param	id		path 	string	true		"项目id"
// @Param	p		query 	int	true		"第几页"
// @Param	pageoffset		query 	int			"每页数"
// @Param	keyword		query 	string			"关键字"
// @Param	type		query 	string			"分类"
// @Param	degree		query 	string			"重要程度"
// @Param	moduleid	query 	string			"模块"
// @Param	acceptid		query 	string			"指派人"
// @Param	status		query 	string			"状态"
// @Success 200 {object} cases.TestCaseDto   int   int  int
// @Failure 403 case not exist
// @router /:id/page [get]
func (u *CaseController) Page() {
	page, err := u.GetInt("p")
	if err != nil {
		page = 1
	}
	offset, err := u.GetInt("pageoffset")
	if err != nil {
		offset = 15
	}
	id, err := u.GetInt64(":id")
	if err != nil {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "未选择对应的项目" + err.Error()}
		u.ServeJSON()
		return
	}
	keyword := u.GetStrings("keyword")
	typec := u.GetStrings("type")
	acceptid := u.GetStrings("acceptid")
	degree := u.GetString("degree")
	status := u.GetString("status")
	moduleid := u.GetString("moduleid")
	condArr := make(map[string]interface{})
	condArr["projectid"] = id
	condArr["keyword"] = keyword
	condArr["typec"] = typec
	condArr["acceptid"] = acceptid
	condArr["degree"] = degree
	condArr["status"] = status
	condArr["moduleid"] = moduleid
	countUser := CasePageCountExec(condArr, page, offset)
	paginator := pagination.SetPaginator(u.Ctx, offset, countUser)
	modeData := CasePageExec(condArr, page, offset)
	type data struct {
		Modules  []TestCaseDto
		Total    int64
		PageNums int
		Page     int
	}
	d := &data{modeData, paginator.Nums(), paginator.PageNums(), paginator.Page()}
	var responseEntity cores.ResponseEntity
	u.Data["json"] = responseEntity.Build(d).Data
	u.Ctx.Output.Status = responseEntity.StatusCode
	u.ServeJSON()
}

type CaseStepDTO struct {
	Id            int64 `json:"Id,string"`
	Projectid     int64 `json:"Projectid,string"`
	Projectname   string
	Moduleid      int64 `json:"Moduleid,string"`
	Modulename    string
	Name          string
	Type          int64 `json:"Type,string"`
	Degree        int64 `json:"Degree,string"`
	Acceptid      int64 `json:"Acceptid,string"`
	Version       int64 `json:"Version,string"`
	Preconditions string
	Remarks       string
	Attachment    string
	Status        int `json:"Status,string"`
	TestCaseStep  []TestCaseStep
}

// 如果你的 struct 实现了接口 validation.ValidFormer
// 当 StructTag 中的测试都成功时，将会执行 Valid 函数进行自定义验证
func (u *CaseStepDTO) Valid(v *validation.Validation) {
	v.Required(u.Name, "name").Message("用例名称不能为空")
	v.Required(u.Projectid, "Projectid").Message("项目不能为空")
}

// @Title Create和修改 用例
// @Description create 用例
// @Param	body		body 	cases.CaseStepDTO	true		"body for case content"
// @Success 200 {string} string
// @Failure 403 body is empty
// @router / [post]
func (u *CaseController) Create() {
	var f CaseStepDTO
	err := json.Unmarshal(u.Ctx.Input.RequestBody, &f)
	// 开始校验输入值
	valid := validation.Validation{}
	b, err := valid.Valid(&f)
	if err != nil {
		// handle error
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "严重异常" + err.Error()}
		u.ServeJSON()
		return
	}
	if !b {
		var validMsg []string
		// validation does not pass
		for _, err := range valid.Errors {
			validMsg = append(validMsg, err.Message)
			log.Println(err.Key, err.Message)
		}
		if !utils.IsEmpty(validMsg) {
			u.Data["json"] = map[string]interface{}{"code": 0, "message": strings.Join(validMsg, ",")}
			u.ServeJSON()
			return
		}
	}
	exists, err1 := GetCaseByname(f.Name)
	if err1 != nil {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "查询数据异常"}
		u.ServeJSON()
		return
	} else if !utils.IsEmpty(f.Id) && exists.Id != f.Id {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "case重复"}
		u.ServeJSON()
		return
	} else if !utils.IsEmpty(exists.Id) && utils.IsEmpty(f.Id) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "case重复"}
		u.ServeJSON()
		return
	}
	userid := u.BaseController.UserUserId
	id, err1 := AddCases(userid, f)
	if err1 == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "信息添加成功", "id": fmt.Sprintf("%d", id)}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "信息添加失败"}
	}
	u.ServeJSON()
}

// @Title Get
// @Description get case by id
// @Param	id		path 	string	true		"The key for case"
// @Success 200 {object} cases.CaseStepDTO
// @Failure 403 :id is empty
// @router /:id [get]
func (u *CaseController) Get() {
	uid := u.GetString(":id")
	if uid != "" {
		var responseEntity cores.ResponseEntity
		int64, err := strconv.ParseInt(uid, 10, 64)
		if err != nil {
			u.Data["json"] = responseEntity.BuildError(err.Error())
			return
		}
		step := new(CaseStepDTO)
		modeData, err := GetCase(int64)
		utils.SimpleCopyProperties(step, modeData)
		caseStep, err := GetCaseStepByCaseId(modeData.Id)
		step.TestCaseStep = caseStep
		if err != nil {
			u.Data["json"] = responseEntity.BuildError(err.Error())
		} else {
			u.Data["json"] = responseEntity.Build(step).Data
			u.Ctx.Output.Status = responseEntity.StatusCode
		}
	}
	u.ServeJSON()
}
